<?php
/**
 * 固定传播基金主线模型
 * @author qianxun
 *
 */
class spreadProcessModel extends MY_Model {
    function spreadProcessModel() {
        parent::MY_Model();
        $this->table = 'SpreadProcess';
    }
    /**
     * 包装数据
     * {@inheritDoc}
     * @see MY_Model::packing()
     */
    function packing($list = array()){
        //组装专营店类型数据
        $storeIds = array();
        foreach ($list as $v){
            $storeIds[] = (int)$v['storeId'];
        }
        $this->CI->load->model('spreadStoreModel');
        $storeByIdList = $this->CI->spreadStoreModel->getListByStoreIds($storeIds);
        //角色列表
        $roleList = $this->config->item('roleList');
        //审核结果
        $auditRs = $this->config->item('spreadBudgetAuditRs');
        foreach ($list as $k => $v){
            //专营店类型
            $v['storeTypeStr'] = isset($storeByIdList[$v['storeId']]) ? $storeByIdList[$v['storeId']]['storeTypeStr'] : '协办店';
            //专营店列表
            $v['storeList'] = unserialize($v['storeList']);
            //年度申请总金额
            $v['yearTotalMoney'] = 0;
            //专营店申请总金额
            $v['applyTotalMoney'] = 0;
            if ($v['storeList']){
                foreach ((array)$v['storeList'] as $storeK => $storeV){
                    $v['yearTotalMoney'] += $storeV['yearMoney'];
                    $v['applyTotalMoney'] += $storeV['applyMoney'];
                }
            }
            //投放类型
            $v['sendType'] = (count((array)$v['storeList']) > 1 || $v['id'] != $v['belongProcId']) ? '联合投放' : '单店投放';
            //扣罚金额
            $v['lostMoney'] = unserialize($v['lostMoney']);
            //审核进度
            if ($v['auditRs'] >= 0){
                $v['auditRoleStr'] = isset($roleList[$v['auditRole']]) ? $roleList[$v['auditRole']].'已审核' : '待审核';
            }else{
                $v['auditRoleStr'] = '未提交';
            }
            //审核结果
            $v['auditRsStr'] = isset($auditRs[$v['auditRs']]) ? $auditRs[$v['auditRs']] : '';
            $list[$k] = $v;
        }
        return $list;
    }
    /**
     * 包装后查询列表,并以时间单位为键
     * @param mix $where
     * @return Ambigous
     */
    function getNewListByTimeUnit($where, $limit = NULL, $offset = NULL, $colum = '', $orderby = ''){
        $findList = $this->getList($where, $limit, $offset, $colum, $orderby);
        $list = array();
        foreach ($findList as $k => $v){
            $list[(int)$v['timeUnit']] = $v;
        }
        return $this->packing($list);
    }
    /**
     * 初始化主流程数据
     * @param array $data
     */
    function initData($data = array()){
        if (!isset($data['storeId']) || !$data['storeId']){
            showError('请设置店铺ID');
        }
        if (!isset($data['year']) || !$data['year']){
            showError('请设置年份');
        }
        $procId = $this->upset($data, array('createTime'=>time()));
        if ($procId){
            return $procId;
        }else{
            showError('生成失败');
        }
    }
    /**
     * 审核项目
     * @param number $projectId
     * @param number $auditRs
     * @param array $user
     */
    function audit($procId, $auditData = array(), $user = array()){
        $procId || showError('请选择主线');
        $auditData['auditRs'] > 0 || showError('请选择审核项');
        $findData = $this->getData($procId);
        $findData['auditRole'] <= $user['userRole'] || showError('您的上级已经审核');
        $data = array(
            'auditRole' => $user['userRole'],
            'auditRs' => $auditData['auditRs'],
        );
        if ($this->edit($procId, $data)){
            //每次审核都清除掉细项
            $this->CI->load->model('spreadProItemModel');
            $this->CI->spreadProItemModel->del(array('storeId'=>$findData['storeId'],'projectId !='=>0,'procId'=>$findData['id']),'*');
            
            //审核通过时初始化协办店数据及投放类型双月数据
            if ($auditData['auditRs'] == 1){
                //初始化协办店主线流程数据
                $this->load->model('spreadProcStoreModel');
                $storeList = $this->spreadProcStoreModel->getList(array('procId'=>$procId));
                foreach ($storeList as $v){
                    if ($findData['storeId'] != $v['storeId']){
                        $id = $this->upset(array(
                            'storeId' =>$v['storeId'],
                            'year' => $findData['year'],
                            'timeUnit' => 0,
                        ), array(
                            'belongProcId' => $procId,
                            'auditRs' => $auditData['auditRs'],
                            'auditRole' => $user['userRole'],
                            'storeList' => serialize(array()),
                            'lostMoney' => serialize(array()),
                            'createTime' => time(),
                        ));
                        $this->updateMoney($id);
                    }
                }
                //初始化项目的双月数据
                $this->load->model('spreadProjectModel');
                $projectList = $this->spreadProjectModel->getList(array('procId'=>$procId));
                foreach ($projectList as $v){
                    $this->spreadProjectModel->initItem($v['id']);                    
                }
            }
            //插入审核日志
            $this->load->model('auditLogModel');
            //插入审核日志
            $this->auditLogModel->addLog(51, array(
                'targetId' => $procId,
                'auditRole' => $user['userRole'],
                'auditUid' => $user['userId'],
                'auditRs' => $auditData['auditRs'],
                'auditDes' => $auditData['auditDes'] ? $auditData['auditDes'] : '',
            ));
            
            return true;
        }else{
            return false;
        }
    }
    /**
     * 更新金额
     * @param number $procId
     */
    function updateMoney($procId){
        $findData = $this->getData($procId);
        
        $data = array();
        
        //年度额度
        $this->CI->load->model('importMoneyModel');
        $data['yearMoney'] = $this->CI->importMoneyModel->getMoney($findData['storeId'], 0, 51, $findData['year']);
        //年度申请总金额
        $this->CI->load->model('spreadProcStoreModel');
        $data['applyMoney'] = $this->CI->spreadProcStoreModel->getStoreApplyMoney($findData['storeId'], $findData['belongProcId']);
        //年度审批总金额
        $data['auditMoney'] = $findData['auditRs'] == 1 ? $data['applyMoney'] : 0;
        //年初补贴金额
        $data['preSubsidyMoney'] = min($data['yearMoney'], $data['auditMoney']);
        
        //本双月扣罚金额
        $lostTotalMoney = 0;
        $lostMoney = $this->getLostMoneyList($findData['storeId']);
        foreach ($lostMoney as $v){
            $lostTotalMoney += $v['lostMoney'];
        }
        $data['lostMoney'] = serialize($lostMoney);
        //扣罚金额总和
        $data['lostTotalMoney'] = $lostTotalMoney;
        //实际补贴金额
        $data['actSubsidyMoney'] = $data['preSubsidyMoney'] - $data['lostTotalMoney'];
        $this->edit($procId, $data);
    }
    /**
     * 获取扣罚金额列表
     * @param number $procId
     * @return array
     */
    function getLostMoneyList($storeId){
        $list = array();
        
        $this->CI->load->model('importMoneyModel');
        
        //$list[] = array('year'=>0,'timeUnit'=>0,'timeUnitStr'=>'','lostMoney' => 0);
        $moneyList = $this->CI->importMoneyModel->getList(array('type'=>52,'storeId ='=>$storeId), NULL, NULL, '', 'timeUnit asc');
        if ($moneyList){
            //时间单位配置
            $this->CI->load->model('timeUnitModel');
            $timeUnitList = $this->CI->timeUnitModel->getCacheData('timeUnitList');
            
            foreach ($moneyList as $v){
                $list[(int) $v['timeUnit']] = array(
                    'year' => $v['year'],
                    'timeUnit' => $v['timeUnit'],
                    'timeUnitStr' => isset($timeUnitList[$v['year']][$v['timeUnit']]) ? $timeUnitList[$v['year']][$v['timeUnit']] : '',
                    'lostMoney' => $v['money']
                );
            }
        }
        return $list;
    }
    /**
     * 获取汇总总金额
     * @param number $storeId
     * @param number $year
     */
    function getTotalMoney($storeId, $year){
        $data = array();
        //年度额度
        $data['yearMoney'] = $this->getYearMoney($storeId, $year);
        //项目汇总
        $this->CI->load->model('spreadProjectModel');
        $projectTotal = $this->CI->spreadProjectModel->getTotalMoney($storeId, $year);
        //申请总金额
        $data['applyMoney'] = $projectTotal['applyMoney'];
        //审批金额
        $data['auditMoney'] = $projectTotal['auditMoney'];
        //结算金额
        $data['settleMoney'] = min($data['auditMoney'], $data['yearMoney']);
        //明细项汇总
        $this->CI->load->model('spreadProItemModel');
        $itemTotal = $this->CI->spreadProItemModel->getTotalMoney($storeId, $year);
        //$data['applyMoney'] = $itemTotal['applyMoney'];
        //$data['auditMoney'] = $itemTotal['auditMoney'];
        //扣罚总金额
        $data['lostTotalMoney'] = $itemTotal['lostMoney'];
        //实际补贴金额
        $data['subsidyMoney'] = $data['settleMoney'] > $data['lostTotalMoney'] ? $data['settleMoney'] - $data['lostTotalMoney'] : 0;
        //剩余额度
        $data['surplusMoney'] = $data['yearMoney'] > $data['applyMoney'] ? $data['yearMoney'] - $data['applyMoney'] : 0;
        return $data;
    }
    /**
     * 获取主流程列表，并以专营店ID为主键
     * @param array $where
     * @return array
     */
    function getNewListByStoreId($where = array()){
        $findList = $this->getNewList($where, null, null, '', 'belongProcId asc,id asc');
        
        $list = array();
        foreach ($findList as $k => $v){
            $storeId = (int)$v['storeId'];
            $list[$storeId] = $v;
        }
        return $list;
    }
    /**
     * 获取有效的扣罚金额双月列表
     * @param array $procList
     * @return unknown[]
     */
    function getLostMoneyTimeUnitList($procList = array()){
        $timeUnitIds = array();
        foreach ($procList as $v){
            foreach ($v['lostMoney'] as $timeUnitK => $timeUnitV){
                in_array($timeUnitK, $timeUnitIds) || $timeUnitIds[] = $timeUnitK;
            }
        }
        $this->load->model('timeUnitModel');
        $startTime = $this->config->item('spreadContractStart');
        $endTime = $this->config->item('spreadContractEnd');
        //时间单位配置
        $timeUnitList = $this->timeUnitModel->getStartEntTimeUnitList(strtotime($startTime), strtotime($endTime));
        $newTimeUnitList = array();
        foreach ($timeUnitList as $v){
            in_array($v['id'], $timeUnitIds) && $newTimeUnitList[$v['id']] = $v;
        }
        return $newTimeUnitList;
    }
    /**
     * 分析列表，统计出条件专营店ID集的总和
     * @param array $sellpointIds 专营店id集
     * @param array $list 以专营店id为键的列表
     * @return array
     */
    function countTotalListByStoreIds($storeIds = array(),$list = array()){
        $data = array(
            'yearMoney' => 0,//年度额度
            'applyMoney' => 0,//申请金额
            'auditMoney'=>0,//审批金额
            'preSubsidyMoney'=>0,//结算金额
            'lostTotalMoney' =>0,//扣罚总金额
            'actSubsidyMoney' => 0,//实际补贴金额
        );
        $filterStoreId = array_intersect($storeIds, array_keys($list));
        foreach ($filterStoreId as $storeId){
            if(isset($list[$storeId])){
                $data['yearMoney']   += $list[$storeId]['yearMoney'];
                $data['applyMoney']   += $list[$storeId]['applyMoney'];
                $data['auditMoney']   += $list[$storeId]['auditMoney'];
                $data['preSubsidyMoney']   += $list[$storeId]['preSubsidyMoney'];
                $data['lostTotalMoney']   += $list[$storeId]['lostTotalMoney'];
                $data['actSubsidyMoney']   += $list[$storeId]['actSubsidyMoney'];
            }
        }
        return $data;
    }
}